#!/usr/local/bin/python
# Rob Dennis - Lurchington Q. Delacroix
# Keasby - TV renamer
# Project Homepage: http://code.google.com/p/keasby/

import logging
import time

log = logging.getLogger("rsc_logger")
log.setLevel(logging.DEBUG)
ch = logging.StreamHandler()
ch.setLevel(logging.DEBUG)
##ch.setFormatter(logging.Formatter("%(levelname)s - %(message)s"))
ch.setFormatter(logging.Formatter("%(message)s"))
log.addHandler(ch)

def shape_func_sig(name, args, kwargs):
    """
    assumes args is a tuple, and kwargs is a dict
    """

    assert isinstance(args, tuple)
    if len(args) > 0:
        print_args = ", ".join([str(arg) for arg in args])
    else:
        print_args = ""

    if len(kwargs) > 0:
        print_kwargs = ", ".join(["%s=%s"%(str(k), str(v))
                                    for k, v in kwargs.iteritems()])
    else:
        print_kwargs = ""

    if print_args and print_kwargs:
        delim = ", "

    else:
        delim = ""

    return "%s(%s%s%s)"%(name, print_args, delim, print_kwargs)

def timeit(method):
    """
    Prints the execution time for a function
    """
    def timed(*args, **kw):
        ts = time.time()
        result = method(*args, **kw)
        te = time.time()

        log.debug('result: %2.2f sec', (te-ts))
        return result

    return timed

def trace(func):
    if log.getEffectiveLevel() == logging.DEBUG:
        def callf(*args, **kwargs):
            try:
                log.debug("TRACE START: %s",
                            shape_func_sig(func.__name__, args, kwargs))
                r = func(*args, **kwargs)

            except Exception, msg:
                log.warning("error in: %s: %s -> %s",
                                shape_func_sig(func.__name__, args, kwargs),
                                                msg.__class__.__name__, msg)
                raise

            if r is None:
                log.debug("TRACE END: %s",
                            shape_func_sig(func.__name__, args, kwargs))
            else:
                log.debug("TRACE END: %s = %s", shape_func_sig(func.__name__,
                                                     args, kwargs), r)
            return r
        return callf
    else:
        return func
